package swb.api.com.api;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import swb.api.com.common.exception.SwbException;
import swb.api.com.repository.SmsVerificationCodeRepository;
import swb.api.com.repository.dto.SmsVerificationCode;
import swb.api.com.repository.dto.UserInfo;
import swb.api.com.service.SmsService;
import swb.api.com.service.UserService;
import swb.api.com.vo.Result;
import swb.api.com.vo.req.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.Optional;

/**
 * 用户相关接口控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@Api(tags = "用户管理接口")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private SmsVerificationCodeRepository smsVerificationCodeRepository;

    /**
     * 微信登录接口
     * @param wechatLog 登录请求参数，包含微信登录凭证
     * @return 登录结果，包含用户信息和登录状态
     */
    @PostMapping("/wechat/login")
    @ApiOperation(value = "微信登录", notes = "通过微信授权码进行用户登录")
    public Result<UserInfo> wechatLogin(@RequestBody WechatLog wechatLog) {
        try {
            String code = wechatLog.getCode();
            if (code == null || code.isEmpty()) {
                return Result.error("缺少微信登录凭证");
            }

            // 调用服务层处理微信登录逻辑
            UserInfo userInfo = userService.wechatLogin(code);

            if (userInfo != null) {
                return Result.success(userInfo, "登录成功");
            } else {
                return Result.error("登录失败");
            }
        } catch (Exception e) {
            log.error("微信登录异常", e);
            return Result.error("登录异常：" + e.getMessage());
        }
    }

    /**
     * 根据ID或openid查询用户信息
     * @param id 用户ID（可选）
     * @param openid 用户openid（可选）
     * @return 用户信息
     */
    @GetMapping
    @ApiOperation(value = "查询用户信息", notes = "根据用户ID、openid或手机号查询用户信息")
    public Result<UserInfo> getUserInfo(
            @ApiParam(value = "用户ID") @RequestParam(required = false) Long id,
            @ApiParam(value = "用户openid") @RequestParam(required = false) String openid,
            @ApiParam(value = "用户手机号") @RequestParam(required = false) String mobile) {

        UserInfo userInfo;
        try {
            userInfo = userService.findUserByIdOrOpenidOrMobile(id, openid, mobile);
        } catch (SwbException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("用户查询异常：" + e.getMessage());
        }

        return Result.success(userInfo,"用户查询");
    }


    @PostMapping("/sms/send")
    @ApiOperation(value = "发送短信验证码", notes = "向指定手机号发送短信验证码")
    public Result<String> sendSmsCode(@RequestBody SendSmsRequest request) {
        try {
            String mobile = request.getMobile();
            if (mobile == null || mobile.isEmpty()) {
                return Result.error("手机号不能为空");
            }

            // 检查手机号格式
            if (!mobile.matches("^1[3-9]\\d{9}$")) {
                return Result.error("手机号格式不正确");
            }

            // 发送验证码
            boolean success = smsService.sendVerificationCode(mobile);
            if (success) {
                Optional<SmsVerificationCode> byMobile = smsVerificationCodeRepository.findByMobile(mobile);
                return Result.success(byMobile.get().getCode(), "验证码发送成功");
            } else {
                return Result.error("验证码发送失败");
            }
        } catch (SwbException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("发送短信验证码异常", e);
            return Result.error("发送验证码异常：" + e.getMessage());
        }
    }

    /**
     * 绑定手机号接口
     * @param request 绑定手机号请求参数
     * @return 绑定结果
     */
    @PostMapping("/bind-mobile")
    @ApiOperation(value = "绑定手机号", notes = "用户绑定手机号，如果是新用户则直接注册")
    public Result<UserInfo> bindMobile(@RequestBody BindMobileRequest request) {
        try {
            String mobile = request.getMobile();
            String code = request.getCode();

            if (mobile == null || mobile.isEmpty()) {
                return Result.error("手机号不能为空");
            }

            if (code == null || code.isEmpty()) {
                return Result.error("验证码不能为空");
            }

            // 验证手机号格式
            if (!mobile.matches("^1[3-9]\\d{9}$")) {
                return Result.error("手机号格式不正确");
            }

            // 验证短信验证码
            boolean isValid = smsService.verifyCode(mobile, code);
            if (!isValid) {
                return Result.error("验证码错误或已过期");
            }

            // 绑定手机号
            UserInfo userInfo = userService.bindMobile(request.getUserId(), mobile);
            return Result.success(userInfo, "手机号绑定成功");
        } catch (SwbException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("绑定手机号异常", e);
            return Result.error("绑定手机号异常：" + e.getMessage());
        }
    }

    /**
     * 手机号短信验证码登录接口
     * @param request 登录请求参数
     * @return 登录结果
     */
    @PostMapping("/sms/login")
    @ApiOperation(value = "短信验证码登录", notes = "通过手机号和短信验证码进行用户登录")
    public Result<UserInfo> smsLogin(@RequestBody SmsLoginRequest request) {
        try {
            String mobile = request.getMobile();
            String code = request.getCode();

            if (mobile == null || mobile.isEmpty()) {
                return Result.error("手机号不能为空");
            }

            if (code == null || code.isEmpty()) {
                return Result.error("验证码不能为空");
            }

            // 验证手机号格式
            if (!mobile.matches("^1[3-9]\\d{9}$")) {
                return Result.error("手机号格式不正确");
            }

            // 执行登录
            UserInfo userInfo = userService.smsLogin(mobile, code);

            return Result.success(userInfo, "登录成功");
        } catch (SwbException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("短信登录异常", e);
            return Result.error("登录异常：" + e.getMessage());
        }
    }
}
